package handlers

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"swu.com/80p/internal/dbs"
)

// 查看详情接口的 Gin Handler
func GetByIdHandler(c *gin.Context) {
	tableName := c.Param("tableName")
	id := c.Param("id")
	primaryKeyName := getPrimayKey(c.Query("primaryKeyName"))

	var result map[string]interface{}
	query := fmt.Sprintf("%s = ?", primaryKeyName)
	// 使用 Take() 而不是 First()，并将结果扫描到 map 中
	dbResult := dbs.GetDB().Table(tableName).Where(query, id).Take(&result)

	if dbResult.Error != nil {
		errResult := getGinError(dbResult.Error)
		if errors.Is(dbResult.Error, gorm.ErrRecordNotFound) {
			c.JSON(http.StatusNotFound, errResult)
			return
		}
		c.JSON(http.StatusInternalServerError, errResult)
		return
	}

	if dbResult.RowsAffected == 0 {
		c.JSON(http.StatusNotFound, getGinError(errors.New("record not found")))
		return
	}

	c.JSON(http.StatusOK, getGinResult(result))
}
